﻿using CnBlogsClient.Database;
using CnBlogsCore.Interface;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace CnBlogsClient.Global
{
    class AuthConfig
    {
        private CnBlogsClient.Database.Models.ClientCredentials _clientCredential;

        public void Initialize()
        {
            _clientCredential = DependencyService.Get<IDatabase>().GetCredentialsAsync();
            if (null == _clientCredential)
            {
                _clientCredential = new Database.Models.ClientCredentials();
                GetNewClientCredential();
            }
        }

        public  string GetClientCredentialToken()
        {
            if (!_clientCredential.IsExpires)
            {
                return _clientCredential.AccessToken;
            }

            GetNewClientCredential();

            return _clientCredential.AccessToken;
        }

        public string GetClientCredentialTokenType()
        {
            if (!_clientCredential.IsExpires)
            {
                return _clientCredential.TokenType;
            }

            GetNewClientCredential();

            return _clientCredential.TokenType;
        }

        private void GetNewClientCredential()
        {
            CnBlogsCore.Model.ClientCredentials newClientCredential =
                      DependencyService.Get<IClientCredentialsService>().GetClientCredential();
            SetClientCredentials(newClientCredential);
        }

        private void SetClientCredentials(CnBlogsCore.Model.ClientCredentials clientCred)
        {
            if (null == clientCred)
            {
                return;
            }

            _clientCredential.AccessToken = clientCred.AccessToken;
            _clientCredential.ExpiresIn = clientCred.ExpiresIn;
            _clientCredential.TokenType = clientCred.TokenType;
            _clientCredential.Scope = clientCred.Scope;
            _clientCredential.GenerateTime = clientCred.GenerateTime;

            DependencyService.Get<IDatabase>().SaveCredentialAsync(_clientCredential);
        }
    }
}
